package cn.yeziji.forum.utils;

import cn.yeziji.forum.common.enums.status.TokenStatus;
import cn.yeziji.forum.exception.TokenException;
import cn.yeziji.forum.exception.UserException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * 用户在线信息工具类
 *
 * @author hwy
 * @since 2023/06/20 14:54
 **/
public class UserOnlineUtils {
  private static final ThreadLocal<String> CURRENT_TOKEN = new ThreadLocal<>();

  public static String getToken() {
    return CURRENT_TOKEN.get();
  }

  public static void clear() {
    CURRENT_TOKEN.remove();
  }

  public static void setToken(String token) {
    CURRENT_TOKEN.set(token);
  }

  public static String getNickName() {
    return getInfoByToken("nickname");
  }

  public static String getUserName() {
    return getInfoByToken("username");
  }

  public static Integer getUserId() {
    return JwtOperaUtils.getTokenClaimByToken(getToken(), "id", Integer.class);
  }

  public static String getInfoByToken(String key) {
    String token = getToken();
    if (StringUtils.isNotBlank(token)) {
      return JwtOperaUtils.getTokenClaimByToken(token, key, String.class);
    }
    throw new TokenException(TokenStatus.TOKEN_INVALID);
  }
}
